﻿using System;
using System.Collections.Generic;
using System.Text;
using EnCor.ObjectBuilder;

namespace EnCor.Security
{
    [AssembleConfig(typeof(MemoryCachedTokenProviderConfig))]
    public class MemoryCachedTokenProvider : TokenProvider
    {
        private Dictionary<string, EnCorIdentity> _Dictionary = new Dictionary<string, EnCorIdentity>();
        /// <summary>
        /// Generates the token.
        /// </summary>
        /// <param name="identity">The identity.</param>
        /// <returns></returns>
        public override string GenerateToken(EnCorIdentity identity)
        {
            Guid token = Guid.NewGuid();
            string tokenString = token.ToString();
            _Dictionary.Add(tokenString, identity);
            return tokenString;
        }

        /// <summary>
        /// Gets the identityby token.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public override EnCorIdentity GetIdentitybyToken(string token)
        {
            if (_Dictionary.ContainsKey(token))
            {
                return _Dictionary[token];
            }
            return null;
        }

        public override UserIdentity Authenticate(Credential credential)
        {
            TokenCredential tokenCredential = credential as TokenCredential;
            if (tokenCredential == null)
            {
                return null;
            }
            return GetIdentitybyToken(tokenCredential.Token);
        }
    }

    [Assembler(typeof(MemoryCachedTokenProviderAssembler))]
    public class MemoryCachedTokenProviderConfig : AuthenticationProviderConfig
    { 
        
    }

    public class MemoryCachedTokenProviderAssembler : IAssembler<IAuthenticationProvider, AuthenticationProviderConfig>
    {
        #region IAssembler<ITokenProvider,TokenProviderConfig> Members

        public IAuthenticationProvider Assemble(IBuilderContext context, AuthenticationProviderConfig objectConfiguration)
        {
            return new MemoryCachedTokenProvider();
        }

        #endregion
    }

}
